<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <%@ include file="/common/dxp/include/common-base.jsp"%>
  <title>日志数据查询</title>
  <!-- Tell the browser to be responsive to screen width -->
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
</head>

  <!-- Part 一、 以下是body主体内容的模块区域 -->
  <body class="hold-transition ${sysColor} sidebar-mini">
  <div class="wrapper">

	  <!-- top start -->
	  <%@include file="/common/dxp/top.jsp" %>
	  <!-- top end -->
	  <!-- left start -->
	  <%@include file="/common/dxp/left.jsp" %>
	  <!-- left end-->

	  <div class="content-wrapper">
		  <!-- Main start -->
		  <section class="content">
			  <div id="div_hidden_content" class="hidden" style="display:none;">
				  <input name="templateType" type="hidden" value="all"/>
				  <div id="hidden_common_final">
					  <!-- temp="hidden_common_final" start -->
					  <!-- temp="hidden_common_final" end -->
				  </div>
				  <!-- temp="delForm_hidden" start -->
				  <div id="delForm_hidden">
				  </div>
				  <!-- temp="delForm_hidden" end -->
			  </div>
			  <div class="row">
				  <div class="col-xs-12">

					  <!------搜索  start ------->
					  <div class="box box-info">
						  <!--搜索title  start -->
						  <div class="box-header with-border">
							  <h3 class="box-title"><i class="fa fa-search"></i>日志数据查询搜索</h3>
							  <div class="box-tools pull-right">
								  <button type="button" class="btn btn-box-tool" data-widget="collapse"><i
										  class="fa fa-minus"></i></button>
							  </div>
						  </div>
						  <!--搜索title  end -->
						  <div class="box-body"  id="searchForm-box">
							  <form id="searchForm" action="javascript:void(0);">
								  <!-- temp="searchForm_hidden" start -->
								  <div id="searchForm_hidden">
									  <input  type="hidden" name="indexName" value="data-warn">
									  <input  type="hidden" name="indexType" value="log">
									  <input  type="hidden" name="orderCloumn" value="indexDate">
									  <input  type="hidden" name="orderSort" value="desc">
									  <input  type="hidden" name="fileList" class="clean">
									  <input  type="hidden" name="must" class="clean">
								  </div>
								  <!-- temp="searchForm_hidden" end -->

								  <!-- temp="searchForm_content" start -->
								  <div id="searchForm_content" class="form-group" data-temp-code="true"
									   data-temp-type="searchForm" data-temp-form-id="searchForm">
									  <table class="table table-bordered bordercolor">
										  <tbody>
										  <tr>
											  <td class="active" align="right"><label
													  class="form-control-static">日志类型：</label></td>
											  <td>
												  <div class="form-control-static" id="searchForm_input_fieldName">
													  <input type="radio" value="1" name="infoType" checked="checked"> 正常
													  <input type="radio" value="2" name="infoType"> 异常
												  </div>
											  </td>
											  <td class="active" align="right"><label
													  class="form-control-static">发生节点：</label></td>
											  <td>
												  <div class="form-control-static" id="div_check_exesys_box">
													  <input type="checkbox" name="check_exesys" value="receive" checked> 接收服务&nbsp;
													  <input type="checkbox" name="check_exesys" value="gateway"> 网关服务&nbsp;
													  <input type="checkbox" name="check_exesys" value="send"> 发送服务&nbsp;
												  </div>
											  </td>
                                          </tr>
                                          <tr>
											  <td class="active" align="right"><label
													  class="form-control-static">发生时间：</label></td>
											  <td colspan="3">
												  <div class="form-group">
													  <div class="input-group ">
														  <input id="searchForm_input_startDate"  name="input_startDate" maxlength="30" class="form-control clean form_datetime" readonly="readonly" type="text">
														  <span class="input-group-addon"> <i class="fa fa-calendar"></i></span>
														  <span class="input-group-addon"> 至 </span>
														  <input id="searchForm_input_endDate"  name="input_endDate" maxlength="30" class="form-control clean form_datetime" readonly="readonly" type="text">
														  <span class="input-group-addon"> <i class="fa fa-calendar"></i></span>
													  </div>
												  </div>
											  </td>
										  </tr>
										  </tbody>
									  </table>
								  </div>
								  <!-- temp="searchForm_content" end -->
								  <div class="box-footer text-center">
									  <button type="button" class="btn btn-success" onclick="getTableData();"
											  data-temp-event="searchForm_hidden"><i class="fa fa-search"></i> 查询
									  </button>
									   
									  <button type="reset" class="btn btn-warning"
											  onclick="mytools.cleanData('#searchForm');">重置
									  </button>
								  </div>
							  </form>
						  </div>
					  </div>
					  <!------- 搜索 end -------->

					  <!------- 列表 start -------->
					  <div class="box box-success">
						  <!--列表title  start -->
						  <div class="box-header with-border">
							  <h3 class="box-title"><i class="fa fa-table"></i> 查询结果 [共计<span id="dataListTotalCount">0</span>条数据]
							  </h3>
							  <div class="box-tools pull-right">
								  <button type="button" class="btn btn-box-tool" data-widget="collapse"><i
										  class="fa fa-minus"></i></button>
							  </div>
						  </div>
						  <div class="box-body mytab2">
							  <table id="table-list" class="table table-bordered table-hover my-table-list"
									 data-toolbar="#table-toolbar" data-cache="false" data-resizable="false" data-unique-id="es_metadata_id"
									 data-pagination="true" data-page-number="1" data-page-size="10" data-page-list="[10,25,50, 100]" data-show-refresh="true"
									 data-sortable="false" data-show-export="true" data-show-columns="true">
								  <thead>
								  <tr>
									  <th data-formatter="pageNumberFormatter" data-align="center">序号</th>
									  <th data-field="traceId" data-formatter="traceIdFormatter">请求唯一ID</th>
<%--									  <th data-field="level">日志级别</th>--%>
									  <th data-field="infoType" data-formatter="infoTypeFormatter">日志类型</th>
									  <th data-field="exeSys" data-formatter="exeSysFormatter">发生节点</th>
									  <th data-field="requestIp">请求IP</th>
									  <th data-field="indexDate" data-formatter="dateStrRep">发生时间</th>
									  <th data-field="total" data-formatter="sizeStrRepFormatter">大小</th>
									  <th data-field="total" data-formatter="dateStrRepFormatter">耗时(ms)</th>
									  <th data-field="errorMessage" data-formatter="remarkFormatter">备注</th>
									  <th data-field="es_metadata_id" data-formatter="optFormatter">操作</th>
								  </tr>
								  </thead>
							  </table>
						  </div>

					  </div>
					  <!------- 列表 end -------->
				  </div>
			  </div>

			  <div win-title="查看窗口" class="modal fade" id="my_modal_view" tabindex="-2" role="dialog"
				   aria-labelledby="myModalLabel" aria-hidden="true">
				  <div class="modal-dialog" style="width:80%;">
					  <div class="modal-content">
						  <div class="modal-header">
							  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
								  ×
							  </button>
							  <h4 class="modal-title">
								  <font color="red">日志数据</font> 
							  </h4>
							  <form id="viewForm" action="javascript:void(0)">
								  <!-- temp="viewForm_hidden" start -->
								  <div id="viewForm_hidden" style="display:none;"></div>
								  <!-- temp="viewForm_hidden" end -->
							  </form>
						  </div>
						  <div class="modal-body viewForm">

							  <div class="nav-tabs-custom">
								  <ul class="nav nav-tabs" id="myTab-view">
								  </ul>

								  <!-- tab content start -->
								  <div class="tab-content">

									  <div class="tab-pane active" id="tabView_1">
										  <form class="form-horizontal" role="form" id="viewForm1"
												action="javascript:void(0)">

											  <!-- temp="viewForm1_content" start -->
											  <div id="viewForm1_content">
												  <table class="table table-bordered bordercolor">
													  <tbody>
													  <tr>
														  <td>
															  <%--                                                            <label class="form-control-static">存证数据：</label>--%>
															  <div class="form-control-static">
																  <pre style="height: 460px; overflow-y: scroll;"><code id="viewForm1_certificate_data"></code></pre>
															  </div>
														  </td>
													  </tr>

													  </tbody>
												  </table>
											  </div>
											  <!-- temp="viewForm1_content" end -->

										  </form>
									  </div>


								  </div>
								  <!-- tab content e -->
							  </div>
						  </div>
					  </div>
					  <!-- /.modal-content -->
				  </div>
			  </div>

			  <!-- Part 二、以下是template模板定义的模块区域 -->


			  <!-- Part 三、 以下是js模块区域 -->
			  <script>
				  var clickMenu = "log-data-list";
				  var myPage, dataListId, searchFormId;
				  myPage = 5;//定义列表数据
				  dataListId = "dataList";//显示列表数据div的id
				  searchFormId = "searchForm";//搜索表单Id
				  var pageConfig = [1,10];
				  /**
				   * 初始化数据字典，id传入#id 返回值Map用法：dictListMap["userType"][rows[i].userType]
				   */
				  var dictListMap = DictUtil.initDictAndDymic();
					var tableListMap={};
				  var $table=$('#table-list');
				  $(function () {
					  //初始化当天零时时间
					  var timeStamp = new Date(new Date().setHours(0, 0, 0, 0));
					  $("#searchForm_input_startDate").val(timeStamp.format("yyyy-MM-dd hh:mm:ss"));
					  $("#searchForm_select_exeSys").val("receive");
					  //1、加载分页列表数据
					  getTableData();

					  //2、控制是否启用token
					  //setToken();

				  });
				  function getExeSysCheckArray(){
					  var exeSysArr = [];
					  $('#div_check_exesys_box').find("input[type='checkbox']:checked").each(function () {
							exeSysArr.push($(this).val());
					  });
					  return exeSysArr;
				  }
				  $('#div_check_exesys_box').find("input[type='checkbox']").click(function (e) {

				  });
				  function traceIdFormatter(value,row) {
					var rest = value;
					if(!strUtil.isNull(row.interfaceCode)){
						rest+="<br/>"+row.interfaceCode;
					}
					return rest;
				  }
				  //发生时间
				  function dateStrRep(str){
				  	if(strUtil.isNull(str)){
				  		return '';
					}
				  	return  str.replace(/T/g,' ').replace(/Z/g,'');
				  }
				  function getContentSize(leng) {
					  leng = leng*1;
					  var re = leng*1;
					  if (leng >= (1024 * 1024 * 1024)) {
						  re = (leng/(1024 * 1024 * 1024)).toFixed(2) + " G";
					  } else if (leng >= (1024 * 1024)) {
						  re = (leng/(1024 * 1024)).toFixed(2) + " M";
					  } else if (leng >= (1024)) {
						  re = (leng/(1024)).toFixed(2)+ " KB";
					  } else {
						  re = leng + " 字节";
					  }
					  return re;
				  }
				  //大小
				  function sizeStrRepFormatter(str,row) {
					  var res = '';
					  var exesys = strUtil.doNull(row.exeSys,"send");
					  if(exesys=="receive"){
						  if(row.responseBody){
							  var responseBodyStr = JSON.stringify(row.responseBody);
							  res+=getContentSize(strUtil.getLength(responseBodyStr));
						  }
					  }
					  return res;
				  }
				  //获取序号
				  function pageNumberFormatter(value, row, index) {
					  //获取每页显示的数量
					  var pageSize=$table.bootstrapTable('getOptions').pageSize;
					  //获取当前是第几页
					  var pageNumber=$table.bootstrapTable('getOptions').pageNumber;
					  console.log('pageNumberFormatter',pageNumber,pageSize);
					  //返回序号，注意index是从0开始的，所以要加上1
					  return pageSize * (pageNumber - 1) + index + 1;
				  }
				  //耗时
				  function dateStrRepFormatter(str,row) {
					var res = '';
					var exesys = strUtil.doNull(row.exeSys,"send");
					var total = strUtil.doNull(row.total,"20");
					if(exesys=="receive"){
						res = total+' ms';
					}
					return res;
				  }
				  //备注
				  function remarkFormatter(value,row) {
				  	var rest = strUtil.doNull(row.nodeName,'');
				  	if(!strUtil.isNull(rest)){
						rest+="_";
					}
					  rest += strUtil.doNull(value,'');
					  return rest;
				  }
				  //操作
				  function optFormatter(value,row) {
					return '<button type="button" class="btn btn-success btn-xs" onclick="toLoadRow(\''+value+'\')"><i class="fa fa-search-plus"></i> 查看</button>'
				  }
				  //日志类型
				  function infoTypeFormatter(value){
					  if(value=='warning'){
						  return "异常";
					  }else if(value=='info'){
						  return "正常";
					  }else{
						  return "错误";
					  }
				  }
				  //发生节点
				  function exeSysFormatter(value, row, index){
					  var exesys = strUtil.doNull(row.exeSys,"send");
					  var sysName ="发送服务";
					  if(exesys=="receive"){
						  sysName = "接收服务";
					  } else if(exesys=="gateway"){
						  sysName = "网关服务";
					  }
					  return sysName+'('+strUtil.doNull(row.ipAddress,'')+')';
				  }

				  $(function () {
					  //设置数据行选中效果
					  $('#' + dataListId + ' tbody').on('click', 'tr', function (e) {
						  if ($(this).hasClass('selected')) {
						  } else {
							  $('tr.selected').removeClass('selected');
							  $(this).addClass('selected');
						  }
						  //var id = $('tr.selected th').eq(0).html();
					  });
				  });
				  //注入日历框样式
				  $('.form_datetime').datetimepicker({
					  // container: ".modal-content",
					  format: 'yyyy-mm-dd hh:ii:ss',
					  /* minView: "month",  *///选择日期后，不会再跳转去选择时分秒
					  language: 'zh-CN',
					  dateFormat: 'yyyy-mm-dd',//日期显示格式
					  timeFormat: 'HH:mm:ss',//时间显示格式
					  todayBtn: 1,
					  autoclose: 1,
					  minView: 0,  //0表示可以选择小时、分钟   1只可以选择小时
					  minuteStep: 5,//分钟间隔1分钟
					  endDate: new Date()
				  });


				  //给模态窗口内form表单内的所有支持必填项的元素注入校验
				  $(".modal").on('shown.bs.modal', function () {
					  $(this).find("form").each(function () {
						  var formId = $(this).attr("id");
						  if (!strUtil.isNull(formId)) {
							  formId = "#" + formId;
							  setValidate(formId);//定义add表单验证属性
							  mytools.cleanValidate(formId);//清空上次校验规则提示
						  }
					  });
				  });


				  //数据toLoad读取（查看、编辑）数据
				  function toLoad(esMetadataId) {
					  var thisRows=$table.bootstrapTable('getRowByUniqueId',esMetadataId);
					  console.log('thisRows',thisRows);
				  	// console.log(tableListMap,"tableListMap");
					  $("#my_modal_view").modal("show");
						var data = tableListMap[esMetadataId];
						// console.log(data,"data--fpc");
					  //反显加载数据
					  if (data) {
						  mytools.showJsonViewer(data,"viewForm1_certificate_data");
						  // $("#viewForm1_certificate_data").text();
					  }else {
						  $("#viewForm1_certificate_data").text("未查询到日志数据");
					  }
				  }
				  //查看行
				  function toLoadRow(esMetadataId) {
					  var thisRows=$table.bootstrapTable('getRowByUniqueId',esMetadataId);
					  console.log('toLoadRow',thisRows);
					  // console.log(tableListMap,"tableListMap");
					  $("#my_modal_view").modal("show");
					  if (thisRows) {
						  mytools.showJsonViewer(thisRows,"viewForm1_certificate_data");
						  // $("#viewForm1_certificate_data").text();
					  }else {
						  $("#viewForm1_certificate_data").text("未查询到日志数据");
					  }

				  }
					function formatDataSoure(str) {
						return str.replace(" ","T")+".000";
					}

				  //加载列表数据
				  function getTableData() {
					  var flag=false;
					  var index_load = layer.load(1, {shade: false});
					  var mustArray = [];
					  var infoType =$("#searchForm_input_fieldName").find("input[name='infoType']:checked").val();
					  switch (infoType) {
						case '1':
							mustArray.push({"terms":{"infoType":["info"]}});
							break;
						case '2':
							mustArray.push({"terms":{"infoType":["warning","exception"]}});
							break;
					  }
				  // ,{"terms":{"exeSys":["receive","gateway"]}}
					  var exeSysArr = getExeSysCheckArray();
					  if(exeSysArr.length>0){
						  mustArray.push({"terms":{"exeSys":exeSysArr}});
					  }
					  var rangeObj={};
					  var lte = $("#searchForm_input_endDate").val();//小于等于
					  var gte=$("#searchForm_input_startDate").val();//大于等于
					  if(gte || lte){
						  rangeObj={indexDate:{}};
						  if(lte){
							  rangeObj.indexDate['to']=formatDataSoure(lte);
						  }
						  if(gte){
							  rangeObj.indexDate['from']=formatDataSoure(gte);
						  }
						  mustArray.push({range:rangeObj});
					  }
					  console.log(infoType,exeSysArr,mustArray);
					  $("#" + searchFormId).find("input[name='must']").val(JSON.stringify(mustArray));
                      $table.bootstrapTable('destroy');
					  $table.bootstrapTable({
						  url:ctx+"/api/esSearchPageList",
						  sidePagination:"server",
						  queryParamsType:'undefined',//采用服务端分页方式为此值
						  queryParams:function (params) {//请求服务器数据参数
							  // console.log("bootstrapTable.params.old->",params);
							  var param =  FormUtil.serializeJson("#"+searchFormId);
							  param.page=strUtil.doNull(params.pageNumber,pageConfig[0]);
							  param.rows=strUtil.doNull(params.pageSize,pageConfig[1]);
							  console.log("bootstrapTable.params->",param);
							  return param;
						  },
						  exportDataType: "all", //basic', 'all', 'selected'.
						  exportOptions:{
							  ignoreColumn: [0],//导出时忽略第一列
							  fileName:'日志数据查询结果'
						  },
						  exportTypes:['excel','json','csv'],//导出类型
						  onLoadSuccess: function(data){//加载成功时执行
							  console.log("bootstrapTable.onLoadSuccess",data);
							  $("#dataListTotalCount").text(data.total);
							  // if(data.total>0){
								//   saveTableListMapData(data.rows);
							  // }
						  },
						  onLoadError: function(status){//加载失败时执行
							  console.log("bootstrapTable.onLoadError",status);
						  },
						  onRefresh: function(param){//加载失败时执行
							  console.log("bootstrapTable.onRefresh",param);
						  },
						  onPageChange: function onPageChange(number, size) {
							  pageConfig=[number,size];
							  console.log("bootstrapTable.onPageChange",number,size);
						  }
					  });
					  layer.close(index_load);
				  }

				  function saveTableListMapData(data){
				  	// console.log(data,"fpc001");
				  	for (var i=0;i<data.length;i++){
				  		var key = data[i].es_metadata_id;
				  		// console.log(key,"key");
						tableListMap[key]=data[i];
					}
				  }


				  //刷新
				  function refresh() {
					  $table.bootstrapTable("refresh");
				  }

				  //设置token
				  function setToken() {
					  $.ajax({
						  type: 'get',
						  url: '${ctx}/sendPage/token?token=true',
						  dataType: 'text',
						  success: function (myData) {
							  console.log(myData);
							  $('.formToken').val(myData);
						  }
					  });
				  }


				  /**** Part 四、以下是自定义新增方法  ****/
//1.定义校验规则-定义
				  function setValidate(id) {
					  $(id).each(function () {
						  $(this).bootstrapValidator({
							  feedbackIcons: {
								  valid: 'glyphicon glyphicon-ok',
								  invalid: 'glyphicon glyphicon-remove',
								  validating: 'glyphicon glyphicon-refresh'
							  }, /** 以下需要结合实际业务清空补充个表单元素的验证规则 **/
							  fields: {
								  /** 可自定义新增验证规则
								   "uctUser.userEname":{
		    		 validators: {
		    			 regexp: {
		    				 regexp: /^[0-9]+$/,
		                      message: '只能是数字'
		                  }
		              }
		    	}
								   **/
							  }
						  });
					  });
				  }


			  </script>
		  </section>
		  <!-- Main end -->
	  </div>
	  <!-- foot start -->
	  <%@include file="/common/dxp/foot.jsp" %>
	  <!-- foot start -->
  </div>
  <!-- /.content-wrapper -->
  </body>
  </html>

